package com.woniu.controller;

import com.woniu.entity.CategoryCourse;
import com.woniu.entity.Course;
import com.woniu.entity.PageResult;
import com.woniu.entity.vo.CourseVO;
import com.woniu.service.CourseService;
import com.woniu.utils.ResultObj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

import static cn.dev33.satoken.SaManager.log;


/**
 * (Course)表控制层
 *
 * @author makejava
 * @since 2025-06-09 18:58:14
 */
@RestController
@RequestMapping("api/course")
@CrossOrigin
public class CourseController {
    /**
     * 服务对象
     */
    @Autowired
    private CourseService courseService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public ResponseEntity<Course> queryById(@PathVariable("id") Long id) {
        return ResponseEntity.ok(this.courseService.queryById(id));
    }

    /**
     * 通过课程ID获取课程信息
     */
    @GetMapping("getCourseById/{courseId}")
    public ResultObj getCourseVOById(@PathVariable Integer courseId){
        CourseVO courseVO = courseService.getCourseVOById(courseId);
        return ResultObj.ok(courseVO);
    }

    /**
     * 查询所有课程，用于课程中心的课程列表
     */
    @GetMapping("findAll")
    public ResultObj findAllCourse(Integer pageNum, Integer pageSize){
        return ResultObj.ok(courseService.findAllCourse(pageNum, pageSize));
    }
    /**
     * 查询所有课程，用于课程中心的课程列表
     */
    @GetMapping("findAllCourseOrderByViewCount")
    public ResultObj findAllCourseOrderByViewCount(){
        return ResultObj.ok(courseService.findAllCourseOrderByViewCount());
    }
    /**
     * 查询所有课程，用于课程中心的课程列表
     */
    @GetMapping("findAllCourseOrderByBuyCount")
    public ResultObj findAllCourseOrderByBuyCount(){
        return ResultObj.ok(courseService.findAllCourseOrderByBuyCount());
    }

    @GetMapping("courseByIds")
    public ResultObj queryCourseByCourseIdList(Integer categoryId,Integer pageNum, Integer pageSize){
        return ResultObj.ok(courseService.queryCourseByCourseIdList(categoryId,pageNum, pageSize));
    }
    /**
     * 查询所有课程,包含条件查询
     */
    @GetMapping("findByCondition")
    public ResultObj findByCondition(
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String teacherName,
            @RequestParam(required = false) Integer enable,
            @RequestParam("pageNum") Integer pageNum,
            @RequestParam("pageSize") Integer pageSize) {

        return ResultObj.ok(courseService.findByCondition(title, teacherName, enable, pageNum, pageSize));
    }
	/**
     * 后台推荐课程（收藏量前四的课程）
     */
    @GetMapping("getRecommendCourses")
    public ResultObj getRecommendCourses(){
        System.out.println("推荐课程"+courseService.getRecommendCourses());
        return ResultObj.ok(courseService.getRecommendCourses());
    }

    /**
     * 最后欢迎的课程（学习人数前四）
     */
    @GetMapping("getPopularCourses")
    public ResultObj getPopularCourses(){
        System.out.println("最受欢迎课程"+courseService.getPopularCourses());
        return ResultObj.ok(courseService.getPopularCourses());
    }

    /**
     * 新增课程
     */
    @PostMapping("/add")
    public ResultObj addCourse(@RequestBody Course course) {
        try {
            // 验证必填字段
            if (course.getTeacherId() == null) {
                return ResultObj.error();
            }

            // 设置默认值
            course.setCreateTime(new Date());
            course.setUpdateTime(new Date());
            course.setViewCount(0);
            course.setBuyCount(0);
            course.setLearnCount(0);
            course.setCreater("管理员");
            course.setUpdater("管理员");

            int result = courseService.insert(course);
            if (result > 0) {
                return ResultObj.ok(result);
            }
            return ResultObj.error();
        } catch (Exception e) {
            return ResultObj.error();
        }
    }

    /**
     * 修改课程
     */
    @PostMapping("/update")
    public ResultObj updateCourse(@RequestBody Course course) {
        try {
            course.setUpdateTime(new Date());
            course.setUpdater("管理员");

            int result = courseService.update(course);
            if (result > 0) {
                // 更新成功后返回最新的课程信息
                Course updatedCourse = courseService.queryById(course.getId());
                return ResultObj.ok(updatedCourse).msg("课程更新成功");
            } else {
                return ResultObj.error().msg("课程不存在或更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace(); // 打印异常堆栈，便于调试
            return ResultObj.error().msg("更新课程时发生错误: " + e.getMessage());
        }
    }

    /**
     * 删除课程
     */
    @PostMapping("/delete/{id}")
    public ResultObj deleteCourse(@PathVariable Long id) {
        try {
            // 先查询课程是否存在
            Course course = courseService.queryById(id);
            if (course == null) {
                return ResultObj.error().msg("课程不存在");
            }

            // 执行删除操作
            int result = courseService.deleteById(id);
            if (result > 0) {
                return ResultObj.ok("删除课程成功");
            } else {
                return ResultObj.error().msg("删除课程失败");
            }
        } catch (Exception e) {
            log.error("删除课程异常", e);
            return ResultObj.error().msg("删除课程时发生错误: " + e.getMessage());
        }
    }

    /**
     * 添加课程类别关联
     */
    @PostMapping("/addCourseCategory")
    public ResultObj addCourseCategory(@RequestBody Map<String, Object> params) {
        try {
            // 添加调试日志
            log.info("接收到的参数: {}", params);

            Integer courseId = null;
            Integer categoryId = null;

            // 处理不同类型的参数传递
            if (params.get("courseId") instanceof Integer) {
                courseId = (Integer) params.get("courseId");
            } else if (params.get("courseId") != null) {
                courseId = Integer.valueOf(params.get("courseId").toString());
            }

            if (params.get("categoryId") instanceof Integer) {
                categoryId = (Integer) params.get("categoryId");
            } else if (params.get("categoryId") != null) {
                categoryId = Integer.valueOf(params.get("categoryId").toString());
            }

            if (courseId == null || categoryId == null) {
                log.error("参数不能为空: courseId={}, categoryId={}", courseId, categoryId);
                return ResultObj.error().msg("参数不能为空");
            }

            // 检查是否已存在相同关联
            CategoryCourse exist = courseService.checkCategoryCourseExist(courseId, categoryId);
            if (exist != null) {
                return ResultObj.ok().msg("关联已存在");
            }

            CategoryCourse categoryCourse = new CategoryCourse();
            categoryCourse.setCourseId(courseId);
            categoryCourse.setCategoryId(categoryId);

            courseService.addCourseCategory(categoryCourse);
            return ResultObj.ok();
        } catch (Exception e) {
            log.error("添加课程类别关联异常", e);
            return ResultObj.error().msg("添加关联异常: " + e.getMessage());
        }
    }

    /**
     * 获取课程关联的类别
     */
    @GetMapping("/getCourseCategories/{courseId}")
    public ResultObj getCourseCategories(@PathVariable Integer courseId) {
        List<CategoryCourse> list = courseService.getCourseCategories(courseId);
        return ResultObj.ok(list);
    }

    /**
     * 删除课程关联的所有类别
     */
    @DeleteMapping("/deleteCourseCategories/{courseId}")
    public ResultObj deleteCourseCategories(@PathVariable Integer courseId) {
        try {
            courseService.deleteCourseCategories(courseId);
            return ResultObj.ok();
        } catch (Exception e) {
            log.error("删除课程类别关联异常", e);
            return ResultObj.error();
        }
    }

    /**
     * 收藏榜TOP5课程
     */
    @GetMapping("/favoriteRankings")
    public ResultObj getFavoriteRankings() {
        return ResultObj.ok(courseService.getFavoriteRankings());
    }

    // 根据老师id查找课程数量
    @PostMapping("/countByTeacher")
    public ResultObj countByTeacher(@RequestBody Map<String, Long> params) {
        Long teacherId = params.get("teacherId");
        int count = courseService.countByTeacherId(teacherId);
        return ResultObj.ok( count);
    }

    //根据老师id查询课程信息
    @GetMapping("/getCourseByTeacherId")
    public ResultObj getCourseByTeacherId(@RequestParam Long teacherId,@RequestParam Integer pageNum,@RequestParam Integer pageSize) {
        PageResult courseByTeacherId = courseService.getCourseByTeacherId(teacherId, pageNum, pageSize);
        return ResultObj.ok(courseByTeacherId);
    }
}



